<template>
    <div id="update-nickname-box">
        <a-form class="nickname-form" :model="nickFormState" ref="formRef" name="update-nickname" :rules="rules"
            @finish="nickFinish" @validate="nickValidate" @finishFailed="nickFinishFailed">
            <a-form-item has-feedback label="" name="newNickname">
                <a-input v-model:value="nickFormState.newNickname" placeholder="请输入昵称" />
            </a-form-item>

            <a-form-item>
                <a-button type="primary" html-type="submit">确认</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script setup>
    import { reactive, defineEmits } from 'vue'
    import { updateNickname } from '@/api/user'
    import { useLoginUserStore } from '@/store/useLoginUserStore'

    const loginUserStore = useLoginUserStore()



    const emit = defineEmits(['custom-event'])
    // 处理修改昵称
    const nickFormState = reactive({
        newNickname: ''
    })
    let space_reg = /^\s*$/
    const checkNickname = async (_rule, value) => {
        if (!value) {
            return Promise.reject('请输入昵称')
        }
        if (value.length > 30) {
            return Promise.reject('昵称不能大于30个字符')
        }
        if (space_reg.test(value)) {
            return Promise.reject('昵称不能全是空白字符')
        }
        return Promise.resolve();
    }
    const rules = {
        newNickname: [
            {
                required: true,
                validator: checkNickname,
                trigger: 'change',
            },
        ],
    }
    const nickSubmit = () => {
        updateNickname(nickFormState).then(async res => {
            // console.log(res.data)
            loginUserStore.fetchLoginUser()
            if (res.data.code !== 0) {
                alert(res.data.msg)
            } else {
                emit('custom-event', 'updated')
            }
        })
    }

    const nickFinish = values => {
        console.log('nickFinish-> ', values)
        nickSubmit()
    }
    const nickFinishFailed = errors => {
        console.log('nickFinishFailed-> ', errors)
    }

    const nickValidate = (...args) => {
        console.log(args)
    }



</script>

<style scoped lang="less">
    #update-nickname-box {
        .nickname-form {
            margin-top: 10px;
            display: flex;
            flex-direction: row;
            width: 100%;
            height: 50px;
        }
    }
</style>